#!/usr/bin/env python3
"""
Dependency installation verification script for OCR service
"""

import subprocess
import sys
import importlib

def run_command(command):
    """Run a command and return the result"""
    try:
        result = subprocess.run(command, shell=True, capture_output=True, text=True)
        return result.returncode == 0, result.stdout, result.stderr
    except Exception as e:
        return False, "", str(e)

def check_package(package_name, import_name=None):
    """Check if a package is installed and importable"""
    if import_name is None:
        import_name = package_name
    
    try:
        module = importlib.import_module(import_name)
        version = getattr(module, '__version__', 'unknown')
        print(f"✓ {package_name}: {version}")
        return True
    except ImportError:
        print(f"✗ {package_name}: NOT INSTALLED")
        return False

def install_stable_dependencies():
    """Install stable dependency versions"""
    print("Installing stable dependencies...")
    
    # First, uninstall conflicting packages
    print("\n1. Removing conflicting packages...")
    uninstall_cmd = "pip uninstall opencv-python opencv-python-headless numpy -y"
    success, stdout, stderr = run_command(uninstall_cmd)
    if success:
        print("✓ Conflicting packages removed")
    else:
        print(f"⚠ Warning during uninstall: {stderr}")
    
    # Install compatible versions step by step
    packages = [
        "numpy>=1.21.0,<2.0.0",
        "opencv-python<=4.6.0.66",
        "paddlepaddle==2.6.0",
        "paddleocr==2.7.3",
        "fastapi==0.104.1",
        "uvicorn[standard]==0.24.0",
        "python-multipart==0.0.6",
        "Pillow==10.1.0",
        "pydantic==2.5.0",
        "pydantic-settings==2.1.0"
    ]
    
    print("\n2. Installing compatible packages...")
    for package in packages:
        print(f"Installing {package}...")
        success, stdout, stderr = run_command(f"pip install {package}")
        if success:
            print(f"✓ {package} installed")
        else:
            print(f"✗ Failed to install {package}: {stderr}")
            return False
    
    return True

def verify_installation():
    """Verify all required packages are installed"""
    print("\n=== Verifying Installation ===")
    
    packages_to_check = [
        ("numpy", "numpy"),
        ("opencv-python", "cv2"),
        ("paddlepaddle", "paddle"),
        ("paddleocr", "paddleocr"),
        ("fastapi", "fastapi"),
        ("uvicorn", "uvicorn"),
        ("PIL", "PIL"),
        ("pydantic", "pydantic")
    ]
    
    all_good = True
    for package_name, import_name in packages_to_check:
        if not check_package(package_name, import_name):
            all_good = False
    
    return all_good

def test_paddleocr():
    """Test PaddleOCR initialization"""
    print("\n=== Testing PaddleOCR ===")
    try:
        from paddleocr import PaddleOCR
        print("✓ PaddleOCR imported successfully")
        
        # Test initialization (this will download models if needed)
        print("Initializing PaddleOCR (this may take a while for first time)...")
        ocr = PaddleOCR(use_angle_cls=True, lang='ch')
        print("✓ PaddleOCR initialized successfully")
        return True
    except Exception as e:
        print(f"✗ PaddleOCR test failed: {e}")
        return False

def main():
    """Main installation and verification process"""
    print("OCR Service Dependency Installation and Verification")
    print("=" * 50)
    
    # Check Python version
    python_version = sys.version_info
    print(f"Python version: {python_version.major}.{python_version.minor}.{python_version.micro}")
    
    if python_version < (3, 8):
        print("✗ Python 3.8 or higher is required")
        return False
    
    # Ask user what to do
    print("\nOptions:")
    print("1. Install stable dependencies (recommended)")
    print("2. Only verify current installation")
    print("3. Test PaddleOCR only")
    
    choice = input("\nEnter your choice (1-3): ").strip()
    
    if choice == "1":
        if install_stable_dependencies():
            print("\n✓ Installation completed!")
        else:
            print("\n✗ Installation failed!")
            return False
    
    if choice in ["1", "2"]:
        if verify_installation():
            print("\n✓ All packages verified!")
        else:
            print("\n✗ Some packages are missing or incompatible!")
            return False
    
    if choice in ["1", "3"]:
        if test_paddleocr():
            print("\n✓ PaddleOCR test passed!")
        else:
            print("\n✗ PaddleOCR test failed!")
            return False
    
    print("\n🎉 Setup completed successfully!")
    print("\nYou can now run the OCR service with:")
    print("python main.py")
    
    return True

if __name__ == "__main__":
    main()